﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Globalization;
using ComClassLibrary;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using KeyboardArg;

namespace CalendarBoard
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _bLoadFinished = false;

        public KeyBoardArgs KeyBoardArgs
        {
            get { return _keyBoardArgs; }
            set { _keyBoardArgs = value; }
        }

        private KeyBoardArgs _keyBoardArgs;

        private const int MSG_NOTIFY_EXIT = 0x400 + 1;

        /// <summary>
        /// 窗口隐藏事件
        /// </summary>
        public event EventHandler Hidden;
        protected void OnWndHidden()
        {
            if (Hidden != null)
            {
                Hidden(this, new EventArgs());
            }
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        public MainWindow(KeyBoardArgs KeyBoardArgs)
        {
            InitializeComponent();
            //MessageBox.Show("test");
            SetKeyBoardArgs(KeyBoardArgs);
            //设置窗体位置
            SetLocation(KeyBoardArgs.ScreenWorkArea);
        }

        public void SetKeyBoardArgs(KeyBoardArgs args)
        {
            //MessageBox.Show("test");
            _keyBoardArgs = args;
            _bLoadFinished = false;           
            labelTitle.Content = _keyBoardArgs.Title.Replace('#',' ');
            date.DisplayMode = CalendarMode.Decade;
            string dateValue = _keyBoardArgs.Content;       
            _bLoadFinished = true;
            if (_keyBoardArgs.DictionaryFileName.Equals("DateBefore"))
            {
                date.DisplayDateEnd = DateTime.Now;
            }
            else if (_keyBoardArgs.DictionaryFileName.Equals("DateLater"))
            {
                date.DisplayDateStart = DateTime.Now;
            }           
        }

        public void SetLocation(System.Drawing.Rectangle rect)
        {
            // 计算窗体在屏幕上的位置，使其位于屏幕中心
            int x = rect.Left + (rect.Width - (int)this.Width) / 2;
            int y = rect.Top + (rect.Height - (int)this.Height) / 2;

            // 设置窗体的位置
            this.Left = x;
            this.Top = y;
        }

        private void date_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_bLoadFinished)
            {
                return;
            }           
            DateTime? dp = date.SelectedDate;
            if (dp == null)
            {
                return;
            }
            if (_keyBoardArgs != null)
            {
                _keyBoardArgs.PassageType = SendMessageType.Response;
                DateTime dt = dp.Value;
                int year = dt.Year;
                string month = dt.Month.ToString().PadLeft(2, '0');
                string day = dt.Day.ToString().PadLeft(2, '0');
                _keyBoardArgs.Content = string.Format("{0}-{1}-{2}", year, month, day);
                _keyBoardArgs.Command = "OK";
                SendMessage();             
                OnWndHidden();
                this.Close();
            }
            else
            {
                this.Close();
            }            
        }

        private bool SendMessage()
        {
            if (_keyBoardArgs.MsgReceiver == IntPtr.Zero)
            {
                MessageBox.Show("句柄错误", "句柄错误");
                return false;
            }
            int uMsg = (int)MessageType.WM_COPYDATA;
            string strMsgText = JsonHandler.ConvertToJsonString(_keyBoardArgs);
         
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strMsgText);
            COPYDATASTRUCT_INTPTR cds = new COPYDATASTRUCT_INTPTR();
            cds.dwData = (IntPtr)uMsg;
            cds.cbData = data.Length;
            cds.lpData = Marshal.AllocHGlobal(data.Length);
            Marshal.Copy(data, 0, cds.lpData, data.Length);
            Message.SendMessage(_keyBoardArgs.MsgReceiver, uMsg, 0, ref cds);
            cds.Free();

            if (_keyBoardArgs.MsgReceiver != _keyBoardArgs.SenderHandle && _keyBoardArgs.SenderHandle != IntPtr.Zero)
            {
                // 通知发送者，程序即将关闭
                string strMsg = "Exit";
                int len = Encoding.Unicode.GetBytes(strMsg).Length;
                COPYDATASTRUCT dataTrans = new COPYDATASTRUCT();
                dataTrans.dwData = (IntPtr)MSG_NOTIFY_EXIT;
                dataTrans.cbData = len;
                dataTrans.lpData = strMsg;
                ComClassLibrary.Message.SendMessage(_keyBoardArgs.SenderHandle, MSG_NOTIFY_EXIT, 0, ref dataTrans);
            }
            return true;
        }

        private void SetDate(string content)
        {
            if (!string.IsNullOrEmpty(content))
            {
                if (content.Length == 10)
                {
                    try
                    {
                        DateTime dt = DateTime.ParseExact(content, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture);
                        if (dt != null)
                        {
                            date.SelectedDate = dt;
                        }                       
                    }
                    catch (Exception)
                    {

                    }
                }               
            }
        }

        private void SetLanguage(string languageCode)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo(languageCode);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-CN");
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("ko-KR");
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("ar-SA");
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
            if (_keyBoardArgs!=null)
            {
                SetLanguage(_keyBoardArgs.LanguageCode);
            }
      
            _bLoadFinished = true;
        }

        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            if (_keyBoardArgs == null)
            {
                this.Close();
                return;
            }
            int uMsg = (int)MessageType.WM_COPYDATA;
            _keyBoardArgs.PassageType = SendMessageType.Response;
            _keyBoardArgs.Content = "";
            _keyBoardArgs.Command = "Cancel";
            string strMsgText = JsonHandler.ConvertToJsonString(_keyBoardArgs);
       
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strMsgText);
            COPYDATASTRUCT_INTPTR cds = new COPYDATASTRUCT_INTPTR();
            cds.dwData = (IntPtr)uMsg;
            cds.cbData = data.Length;
            cds.lpData = Marshal.AllocHGlobal(data.Length);
            Marshal.Copy(data, 0, cds.lpData, data.Length);
            Message.SendMessage(_keyBoardArgs.MsgReceiver, uMsg, 0, ref cds);
            cds.Free();
            if (_keyBoardArgs.MsgReceiver != _keyBoardArgs.SenderHandle && _keyBoardArgs.SenderHandle != IntPtr.Zero)
            {
                // 通知发送者，程序即将关闭
                string strMsg = "Exit";
                int len = Encoding.Unicode.GetBytes(strMsg).Length;          
                COPYDATASTRUCT dataTrans = new COPYDATASTRUCT();
                dataTrans.dwData = (IntPtr)MSG_NOTIFY_EXIT;
                dataTrans.cbData = len;
                dataTrans.lpData = strMsg;
                Message.SendMessage(_keyBoardArgs.SenderHandle, MSG_NOTIFY_EXIT, 0, ref dataTrans);
            }
            this.Close();
            OnWndHidden();
        }
    }
}
